package com.lin.controller;

import com.lin.VO.ResultVO;
import com.lin.config.ProjectUrlConfig;
import com.lin.constant.CookieConstant;
import com.lin.constant.RedisConstant;
import com.lin.dataobject.SellerInfo;
import com.lin.enums.ResultEnum;
import com.lin.server.SellerService;
import com.lin.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.UUID;

import static com.lin.utils.VerificationCodeUtils.strCode;

/**
 * Created by MYQ on 2017/9/20.
 */
@Controller
//@RequestMapping("/")
public class SellerLoginController {
    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    private ByteArrayInputStream bais;
    private VerificationCodeUtils code = null;
    private String strCode = null;

    @RequestMapping("/login")
    public ModelAndView goLogin(){
        return new ModelAndView("login/login");
    }

    @RequestMapping("/")
    public ModelAndView goHome(){
        return new ModelAndView("home/home");
    }

    @ResponseBody
    @RequestMapping(value = "/login/doLogin",method = RequestMethod.POST)
    public ResultVO doLogin(@RequestParam(value = "name", defaultValue = "") String name,
                            @RequestParam(value = "password", defaultValue = "") String password,
                            @RequestParam(value = "checCodeInput", defaultValue = "") String checCodeInput,
                            HttpServletResponse response,
                            Map<String, Object> map, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String code=(String) session.getAttribute("randomCode");
        if (StringUtils.isEmpty(code)){
            return ResultVOUtils.error(ResultEnum.VERIFICATION_CODE_EXPIRED.getCode(),
                    ResultEnum.VERIFICATION_CODE_EXPIRED.getMessage());
        }
        if (code.toLowerCase().equals(checCodeInput.toLowerCase())){
            SellerInfo sellerInfo=sellerService.findByUserName(name);
            if (sellerInfo==null){
                return ResultVOUtils.error(ResultEnum.LOGIN_FAIL.getCode(),
                        ResultEnum.LOGIN_FAIL.getMessage());
            }
            if (sellerInfo.getStatus()==0){
                return ResultVOUtils.error(ResultEnum.USER_NOT_AUDIT.getCode(),
                        ResultEnum.USER_NOT_AUDIT.getMessage());
            }
            if (MD5SaltUtils.validPassword(password,sellerInfo.getPassword())){
                String token = UUID.randomUUID().toString();
                Integer expire = RedisConstant.EXPIRE;
                //设置token到redis，由于公司没有装redis，所以暂时注释掉
//        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), name, expire, TimeUnit.SECONDS);
                //3. 设置token至cookie
                CookieUtil.set(response, CookieConstant.TOKEN, token, expire);
                return ResultVOUtils.success();
            }
            else {
                return ResultVOUtils.error(ResultEnum.LOGIN_FAIL.getCode(),
                        ResultEnum.LOGIN_FAIL.getMessage());
            }
        }
        else {
            return ResultVOUtils.error(ResultEnum.VERIFICATION_CODE_ERROR.getCode(),
                    ResultEnum.VERIFICATION_CODE_ERROR.getMessage());
        }
    }

    @RequestMapping("/login/logout")
    public ModelAndView logout(HttpServletRequest request,
                               HttpServletResponse response,
                               Map<String, Object> map) {
        //1. 从cookie里查询
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null) {
            //2. 清除redis
//            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));

            //3. 清除cookie
            CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
        }
        return new ModelAndView("redirect:" +  "/login");
    }

    @ResponseBody
    @RequestMapping(value="/login/getCode")
    public void getCode(HttpServletResponse response,HttpSession session) throws IOException {

        code = new VerificationCodeUtils();
        bais = code.createImage();
        strCode = code.strCode;

        response.setContentType("image/jpeg");
        InputStream in=bais;
        int len;
        byte[] buf=new byte[1024];
        while((len =in.read(buf,0,1024))!=-1){
            response.getOutputStream().write(buf,0,len);
        }
        session.setAttribute("randomCode", strCode);
        response.getOutputStream().close();
    }


    @RequestMapping("/register")
    public ModelAndView register(){
        return new ModelAndView("register/view");
    }

    @RequestMapping("/agreement")
    public ModelAndView agreement(){
        return new ModelAndView("home/agreement");
    }
}
